import React, { Component } from 'react';
import { Modal, Form, Input, Spin, TreeSelect, Select, message } from 'antd';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/braft.css';
import ImguploadNum from '../../../components/upload/imguploadnum';
import { fileuploadconfig } from 'utils';

const {
	fileupload: { uploadPath, appName },
} = fileuploadconfig;

const FormItem = Form.Item;
const Option = Select.Option;

@Form.create()
export default class AddModal extends Component {
	state = {
		newsMark: false,
		numMark: 1,
	};
	/**
	 * 返回表单数据到父组件
	 */
	onOk = () => {
		this.props.form.validateFields((err, values) => {
			if (!err) {
				this.props.onOk(values);
			}
		});
	};
	/**
	 * 清除表单数据
	 */
	handleFormClear = () => {
		const { form } = this.props;
		form.resetFields();
	};

	//富文本文件上传
	handleUploadFile = param => {
		const serverURL = uploadPath;
		const xhr = new XMLHttpRequest();
		const fd = new FormData();

		// libraryId可用于通过mediaLibrary示例来操作对应的媒体内容
		console.log(param.libraryId);

		const successFn = response => {
			// 假设服务端直接返回文件上传后的地址
			// 上传成功后调用param.success并传入上传后的文件地址
			param.success({
				url: JSON.parse(xhr.responseText).data,
			});
		};

		const progressFn = event => {
			// 上传进度发生变化时调用param.progress
			param.progress((event.loaded / event.total) * 100);
		};

		const errorFn = response => {
			// 上传发生错误时调用param.error
			param.error({
				msg: 'unable to upload.',
			});
		};

		xhr.upload.addEventListener('progress', progressFn, false);
		xhr.addEventListener('load', successFn, false);
		xhr.addEventListener('error', errorFn, false);
		xhr.addEventListener('abort', errorFn, false);

		fd.append('file', param.file);
		fd.append('appName', appName);
		xhr.open('POST', serverURL, true);
		xhr.send(fd);
	};

	onChangeType = value => {
		if (value == 9 || value == 10) {
			this.setState({
				newsMark: true,
				numMark: 1,
			});
			this.props.form.setFieldsValue({
				contentType: 'article',
			});
		} else {
			this.setState({
				newsMark: false,
				numMark: 1,
			});
			this.props.form.setFieldsValue({
				contentType: 'article',
			});
		}
	};

	onChangeContentType = value => {
		if (value === 'articles') {
			this.setState({
				numMark: 3,
			});
		} else {
			this.setState({
				numMark: 1,
			});
		}
	};

	render() {
		const { form, visible, typeTreeData } = this.props;
		const { getFieldDecorator } = form;
		const formItemLayout = {
			labelCol: { span: 6 },
			wrapperCol: { span: 16 },
		};
		const { contentType } = this.state;
		return (
			<Modal
				visible={visible}
				width={720}
				title="新增图文"
				okText="提交"
				cancelText="取消"
				onCancel={this.props.onCancel}
				onOk={this.onOk}
				afterClose={this.handleFormClear}
				destroyOnClose={true}
			>
				<Spin tip="数据加载中..." spinning={false}>
					<Form>
						<FormItem {...formItemLayout} label="标题" hasFeedback>
							{getFieldDecorator('title', {
								rules: [{ required: true, message: '请输入标题！' }],
							})(<Input />)}
						</FormItem>
						<FormItem {...formItemLayout} label="简介" hasFeedback>
							{getFieldDecorator('subtitle', {
								rules: [{ required: true, message: '请输入简介！' }],
							})(<Input />)}
						</FormItem>
						<FormItem {...formItemLayout} label="作者" hasFeedback>
							{getFieldDecorator('author')(<Input style={{ width: 200 }} />)}
						</FormItem>
						<FormItem {...formItemLayout} label="板块" hasFeedback>
							{getFieldDecorator('typeId', {
								rules: [{ required: true, message: '请选择板块！' }],
							})(
								<TreeSelect
									style={{ width: 200 }}
									dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
									treeData={Object.values(typeTreeData)}
									placeholder="请选择"
									treeDefaultExpandAll
									onChange={this.onChangeType}
								/>
							)}
						</FormItem>
						<FormItem {...formItemLayout} label="类别" hasFeedback>
							{getFieldDecorator('contentType', {
								initialValue: 'article',
								rules: [{ required: true, message: '请现在类别！' }],
							})(
								this.state.newsMark ? (
									<Select
										style={{ width: 200 }}
										onChange={this.onChangeContentType}
									>
										<Option value="video">视频</Option>
										<Option value="article">图文</Option>
										<Option value="audio">音频</Option>
										<Option value="bigArticle">大图图文</Option>
										<Option value="articles">多图图文</Option>
									</Select>
								) : (
									<Select
										style={{ width: 200 }}
										onChange={this.onChangeContentType}
									>
										<Option value="video">视频</Option>
										<Option value="article">图文</Option>
										<Option value="audio">音频</Option>
									</Select>
								)
							)}
						</FormItem>

						<FormItem {...formItemLayout} label="上传封面">
							{getFieldDecorator('coverImg', {
								rules: [{ required: true, message: '封面图' }],
							})(
								<ImguploadNum
									fileList={[]}
									uplength={this.state.numMark}
									listType="pics"
								/>
							)}
						</FormItem>

						<FormItem {...formItemLayout} label="图文详情">
							{getFieldDecorator('content', {
								rules: [{ required: false, message: '请输入备注！' }],
							})(
								<BraftEditor
									height={400}
									contentFormat={'html'}
									excludeControls={['emoji']}
									media={{
										allowPasteImage: true, // 是否允许直接粘贴剪贴板图片（例如QQ截图等）到编辑器
										image: true, // 开启图片插入功能
										video: true, // 开启视频插入功能
										audio: true, // 开启音频插入功能
										uploadFn: this.handleUploadFile,
									}}
								/>
							)}
						</FormItem>
					</Form>
				</Spin>
			</Modal>
		);
	}
}
